package com.chinasoftinc.facommon;

import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.ace.ability.AceInternalAbility;
import ohos.agp.utils.TextTool;
import ohos.rpc.MessageOption;
import ohos.rpc.MessageParcel;
import ohos.utils.net.Uri;
import ohos.utils.zson.ZSONObject;

import com.chinasoftinc.facommon.utils.LogUtil;
import com.chinasoftinc.facommon.utils.RemoteUtils;

import java.util.HashMap;

/**
 * 提供JS的工具类
 *
 * @since 2022-05-06
 */
public class CommonAbility extends AceInternalAbility {
    private static final int OPEN_URL = 1001;
    private static final int CODE_NET_CONFIG_OR_DEVICE_PAGE = 1002;
    private static final int REQUEST_HILINK_REGISTER = 1003;
    private static final int OPEN_CONTROL_PAGE = 1004;
    private static final String TAG = "CommonAbility";

    private CommonAbility() {
        super(CommonAbility.class.getPackage().getName(), CommonAbility.class.getName());
    }

    public static CommonAbility get() {
        return InnerClass.INSTANCE;
    }

    public void startServer() {
        setInternalAbilityHandler(this::onRemoteRequest);
    }

    private static final class InnerClass {
        private static final CommonAbility INSTANCE = new CommonAbility();
    }

    private boolean onRemoteRequest(int code, MessageParcel data, MessageParcel reply, MessageOption option) {
        LogUtil.info(TAG, "onRemoteRequest" + code);
        switch (code) {
            case CODE_NET_CONFIG_OR_DEVICE_PAGE:
                HilinkRegister.get().goNetConfigOrDevicePage();
                return RemoteUtils.responseSuccess(reply);
            case OPEN_URL:
                String dataString = data.readString();
                if (TextTool.isNullOrEmpty(dataString)) {
                    LogUtil.warn(TAG, "The url cannot be empty");
                    RemoteUtils.responseError(reply, -1, "The url cannot be empty");
                    return false;
                }
                ZSONObject dataObject = ZSONObject.stringToZSON(dataString);
                String url = dataObject.getString("url");
                if (FAConfigMgr.get().isOpenUrlByInternalWeb()) {
                    openWebPage(url);
                } else {
                    openUrl(url);
                }
                return RemoteUtils.responseSuccess(reply);
            case REQUEST_HILINK_REGISTER:
                HilinkRegister.get().openHiLinkNetConfig();
                return RemoteUtils.responseSuccess(reply);
            case OPEN_CONTROL_PAGE:
                boolean isJumped = false;
                String withParamsString = data.readString();
                if (!TextTool.isNullOrEmpty(withParamsString)) {
                    HashMap<String, Object> hashMap = ZSONObject.stringToClass(withParamsString, HashMap.class);
                    if (hashMap != null) {
                        HilinkRegister.get().openDevicePage(hashMap);
                        isJumped = true;
                    }
                }
                if (!isJumped) {
                    HilinkRegister.get().openDevicePage();
                }
                return RemoteUtils.responseSuccess(reply);

        }
        return false;
    }

    private void openWebPage(String url) {
        FAApplication.getAppContext().getUITaskDispatcher().asyncDispatch(() -> {
            Intent intent = new Intent();
            intent.setParam("url", url);
            Operation operation = new Intent.OperationBuilder().withDeviceId("")
                .withBundleName(FAConfigMgr.get().getBundleName())
                .withAbilityName(FAConfigMgr.get().getInternalWebPageAbilityName())
                .withFlags(Intent.FLAG_ABILITY_NEW_MISSION | Intent.FLAG_INSTALL_ON_DEMAND)
                .build();
            intent.setOperation(operation);
            FAApplication.getAppContext().startAbility(intent, -1);
        });
    }

    private void openUrl(String url) {
        FAApplication.getAppContext().getUITaskDispatcher().asyncDispatch(() -> {
            Intent intent = new Intent();
            Operation operation =
                new Intent.OperationBuilder()
                    .withDeviceId("")
                    .withAction("android.intent.action.VIEW")
                    .withFlags(Intent.FLAG_NOT_OHOS_COMPONENT | Intent.FLAG_ABILITY_NEW_MISSION)
                    .withUri(Uri.parse(url))
                    .build();
            intent.setOperation(operation);
            FAApplication.getAppContext().startAbility(intent, -1);
        });
    }

    public void stopServer() {
        setInternalAbilityHandler(null);
    }
}
